package cn.stronglink.esm27.collection.iot.devices.esm27.response.coder;

import java.nio.ByteBuffer;

import org.jboss.logging.Logger;

import cn.stronglink.esm27.collection.core.util.ByteUtil;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.ESM27ResponseMessageFactory;

public class ESM27Coder {
	Logger logger = Logger.getLogger(ESM27Coder.class);
	private final static int PROTOCOL_MIN_SIZE = 9; // 协议的最小尺寸
	ESM27ResponseMessageFactory factory = new ESM27ResponseMessageFactory();
	/**
	 * 设备地址
	 */
	private byte deviceAddress;

	/**
	 * 设备状态
	 */
	private byte deviceStatus;

	/**
	 * 命令码
	 */
	private byte commandCode;

	/**
	 * 命令执行状态
	 */
	private byte commandRunStatus;
	/**
	 * 数据长度
	 */
	private int dataLen;

	@SuppressWarnings("unused")
	public Object encoder(ByteBuffer buffer) {
		int len = buffer.position();
		// 如果接收数据小于最小协议尺寸，则退出
		if (len < PROTOCOL_MIN_SIZE) {
			return null;
		}

		this.dataLen = ByteUtil.byteToUInt(buffer.get(2));
		if (len < PROTOCOL_MIN_SIZE + this.dataLen) {
			return null;
		}
		short endFlag = 0;
		byte header1 = buffer.get(0);
		byte header2 = buffer.get(1);
		if (header1 == (byte)0xFF && (byte)header2 == 05 && this.dataLen == 28) {
			endFlag = buffer.getShort(33);
		} else {
			endFlag = buffer.getShort(PROTOCOL_MIN_SIZE + this.dataLen - 2);
		}

		buffer.flip(); // 设置buffer.postion=0
		// 如果指定位置不是结束符，将第一个字节请出缓冲区
		if (endFlag != 0x0D0A) {
			buffer.position(1); // 读区一个字节
			buffer.compact(); // 清除读取过的数据
			return null;
		}

//		byte[] crcDatas = new byte[PROTOCOL_MIN_SIZE + this.dataLen - 4];
//		System.arraycopy(buffer.array(), 0, crcDatas, 0, crcDatas.length);

		// 读区协议各字段
		this.deviceAddress = buffer.get();
		this.commandCode = buffer.get();
		this.dataLen = buffer.get();
		byte[] datas = new byte[this.dataLen];
		buffer.get(datas);
//		System.out.println("data postion="+buffer.position());
		if (header1 == (byte)0xFF && (byte)header2 == 05 && this.dataLen == 28) {

		} else {
			this.deviceStatus = buffer.get();
//		System.out.println("deviceStatus postion="+buffer.position());
			this.commandRunStatus = buffer.get();
//		System.out.println("commandRunStatus postion="+buffer.position());
		}
		short crc = buffer.getShort();
//		System.out.println("crc postion="+buffer.position());
		endFlag = buffer.getShort();
//		System.out.println("end postion="+buffer.position());
		buffer.compact(); // 清除读取过的数据

//		short myCrc = ESM27MessageTools.calcCRC(crcDatas);
		
		if (true) {
			Object entity = factory.CreateESM27Entity(deviceAddress, deviceStatus, commandCode, commandRunStatus,
					datas);
			return entity;
		} else {
			return null;
		}
	}
}
